﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using BigEaterCh.Kontrolki;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using LibreOfficeExport;
using Point = System.Drawing.Point;
using System.Collections.Generic;

namespace BigEaterCh
{
  public partial class FormJadlospis : FormZywienie
  {
    private readonly Jadlospis _jad;
    Bitmap _memoryImage;

    private System.IO.Stream streamToPrint;
    List<UserDzien> dni = new List<UserDzien>();


    string streamType;

    [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
    private static extern bool BitBlt
    (
        IntPtr hdcDest, // handle to destination DC
        int nXDest, // x-coord of destination upper-left corner
        int nYDest, // y-coord of destination upper-left corner
        int nWidth, // width of destination rectangle
        int nHeight, // height of destination rectangle
        IntPtr hdcSrc, // handle to source DC
        int nXSrc, // x-coordinate of source upper-left corner
        int nYSrc, // y-coordinate of source upper-left corner
        System.Int32 dwRop // raster operation code
    );

    public FormJadlospis(Jadlospis jad)
    {
      _jad = jad;
      InitializeComponent();

      var tableLayoutPanel2 = new TableLayoutPanel();
      SuspendLayout();
      tableLayoutPanel2.ColumnCount = 7;
      tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
      tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
      tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
      tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
      tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
      tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
      tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
      tableLayoutPanel2.Dock = DockStyle.Fill;
      tableLayoutPanel2.Location = new Point(0, 0);
      tableLayoutPanel2.Name = "tableLayoutPanel2";

      TimeSpan ts = _jad.DataKoncowa - _jad.DataPoczatkowa;

      int dec = ts.Days/7;
      if(ts.Days%7 >0)dec += 1;
      tableLayoutPanel2.RowCount =dec;
      for( int i = 0 ; i < tableLayoutPanel2.RowCount ; i++ )
      {
        tableLayoutPanel2.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
      }

      int indexDay = 0;
      int indexRow = 0;
      while( indexDay<ts.Days )
      {
        for (int i = 0; i < 7; i++)
        {
          if( indexDay<ts.Days )
          {
            var ut = new UserDzien
            {
              ActiveDay = _jad.DataPoczatkowa.AddDays(indexDay + i) ,
              Dock = DockStyle.Fill
            };
            tableLayoutPanel2.Controls.Add(ut, i, indexRow);
            dni.Add(ut);
          }
        }
        indexDay += 7;
        indexRow++;
      }

      tableLayoutPanel2.Size = new Size(834, 620);
      tableLayoutPanel2.TabIndex = 1;
      toolStripContainer1.ContentPanel.Controls.Add(tableLayoutPanel2);
      ResumeLayout(false);
    }

    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
      //e.Graphics.FillRectangle(Brushes.Red,
      //  new Rectangle(500, 500, 500, 500));

       System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint);
      int x = e.MarginBounds.X;
      int y = e.MarginBounds.Y;
      int width = image.Width;
      int height = image.Height;

      if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
      {
          width = e.MarginBounds.Width;
          height = image.Height * e.MarginBounds.Width / image.Width;
      }
      else
      {
          height = e.MarginBounds.Height;
          width = image.Width * e.MarginBounds.Height / image.Height;
      }

      System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
      e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);

    }

    private void wydrukJadłospisuToolStripMenuItem_Click(object sender, EventArgs e)
    {
      //CaptureScreen();
      //printDocument1.Print();

      Graphics g1 = this.toolStripContainer1.ContentPanel.CreateGraphics();

      Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);

      Graphics g2 = Graphics.FromImage(MyImage);

      IntPtr dc1 = g1.GetHdc();

      IntPtr dc2 = g2.GetHdc();

      BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);

      g1.ReleaseHdc(dc1);

      g2.ReleaseHdc(dc2);

      MyImage.Save(@"c:\PrintPage.jpg", ImageFormat.Jpeg);

      FileStream fileStream = new FileStream(@"c:\PrintPage.jpg", FileMode.Open, FileAccess.Read);

      StartPrint(fileStream, "Image");

      fileStream.Close();

      //if( System.IO.File.Exists(@"c:\PrintPage.jpg") )
      //{

      //  System.IO.File.Delete(@"c:\PrintPage.jpg");

      //}
    }

    public void StartPrint(Stream streamToPrint, string streamType)
    {

      this.printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);

      this.streamToPrint = streamToPrint;

      this.streamType = streamType;

      System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();

      PrintDialog1.AllowSomePages = true;

      PrintDialog1.ShowHelp = true;

      PrintDialog1.Document = printDocument1;

      DialogResult result = PrintDialog1.ShowDialog();

      if( result == DialogResult.OK )
      {
        printDocument1.Print();
      }
    }                
                
    private void WordToolStripMenuItemClick(object sender, EventArgs e)
    {
      DateTime start = (from c in dni
                        select c.ActiveDay).Min();
      DateTime stop = (from c in dni
                        select c.ActiveDay).Max();

      var ofd = new SaveFileDialog {Filter = @"*.ods|*.ods", DefaultExt = ".ods", AddExtension = true};
      ofd.FileName = string.Format("Jadłospis {0} - {1}.ods", start.ToShortDateString(), stop.ToShortDateString());

      if(ofd.ShowDialog()==DialogResult.OK)
      {
        try
        {

        List<string[]> dniString = new List<string[]>();
        foreach( var dzien in dni )
        {
          if( dzien.ActiveDay.DayOfWeek==DayOfWeek.Saturday )
            continue;
          if( dzien.ActiveDay.DayOfWeek==DayOfWeek.Sunday )
            continue;

          string [] d = new string[] {dzien.ActiveDay.ToString("dd.MM"),UserDzien.GetDayName(dzien.ActiveDay.DayOfWeek),string.Join(", ", dzien.GetPosilek(EnumPosilek.Sniadanie)),string.Join(", ", dzien.GetPosilek(EnumPosilek.Obiad)),string.Join(", ", dzien.GetPosilek(EnumPosilek.Podwieczorek))} ;
          dniString.Add(d);
        }

        var inFile = new Uri(Path.Combine(System.Windows.Forms.Application.StartupPath, "jadlospis.ods"));
        var outFile = new Uri(ofd.FileName);
        JadlospisExport.CreateJadlospis(inFile, outFile, start, stop, dniString);
        }
        catch (Exception ex )
        {
          MessageBox.Show(ex.Message);
        }
        finally
        {
          MessageBox.Show(@"Eksport zakończono");
          Process.Start(ofd.FileName);
        }
      }
    }

    //private void CaptureScreen()
    //{
    //  Graphics myGraphics = this.toolStripContainer1.ContentPanel.CreateGraphics();
    //  Size s = this.Size;
    //  _memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
    //  Graphics memoryGraphics = Graphics.FromImage(this._memoryImage);
    //  memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
    //}
  }
}
